﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.CUiAssignDataFromTCWindow
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.AssignDataFromTC;
using DnProcessSimulateCommands.AssignDataFromTC.BLModel;
using EngineeringInternalExtension;
using EngineeringInternalExtension.Utilities;
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui.WPF;
using Tecnomatix.Engineering.Utilities;
using UiInternalControls.WPFControls;


namespace DnProcessSimulateCommands;

public class CUiAssignDataFromTCWindow : TxWindow, IComponentConnector, IStyleConnector
{
  private bool _isSearching;
  private List<CUiSearchResultObject> _foundObjects;
  private CApPropertiesManager _propertiesManager;
  private CApAssignDataFromTCApp _application;
  private bool _closing;
  private string _currentSearchProgressMessage = string.Empty;
  private string _currentItemsCountMessage = string.Empty;
  private System.Windows.Controls.Control _lastFocusedControl;
  private string _lastItemIdCriteria = string.Empty;
  private string _lastItemRevisionNameCriteria = string.Empty;
  private CUiConsumeForm _consumeForm;
  private bool _areObjectsLoaded;
  private const string ADFTC_REG_PRODUCTS_SELECTED = "AreProductStructuresSelected";
  protected BomLineModel _model = new BomLineModel();
  private FilterWnd _filterWindow;
  protected SearchProgressModel _searchProgressModel = new SearchProgressModel();
  internal Grid _mainGrid;
  internal System.Windows.Controls.GroupBox _groupBoxSearchScopes;
  internal System.Windows.Controls.ComboBox _comboBoxStructures;
  internal ComboBoxItem _comboBoxItemProduct;
  internal ComboBoxItem _comboBoxItemPlant;
  internal System.Windows.Controls.ListView _listViewScopes;
  internal TextBlock label2;
  internal System.Windows.Controls.TextBox _textBoxItemId;
  internal TextBlock label3;
  internal System.Windows.Controls.TextBox _textBoxItemRevisionName;
  internal System.Windows.Controls.Button _buttonSearch;
  internal System.Windows.Controls.Button _buttonSearchStop;
  internal System.Windows.Controls.GroupBox _groupBoxSearchResults;
  internal System.Windows.Controls.ToolBar _stackPanelResults;
  internal System.Windows.Controls.Button _buttonOptions;
  internal System.Windows.Controls.Button _buttonToolbarClearFilters;
  internal System.Windows.Controls.Button _buttonToolbarDisplaySelected;
  internal System.Windows.Controls.Button _buttonToolbarBlankSelected;
  internal System.Windows.Controls.Button _buttonToolbarDisplayOnlySelected;
  internal System.Windows.Controls.Button _buttonToolbarZoomToSelection;
  internal System.Windows.Controls.Button _buttonToolbarZoomToFit;
  internal System.Windows.Controls.Button _buttonToolbarRestorePosition;
  internal System.Windows.Controls.Button _buttonToolbarRelocate;
  internal BLDataGrid _dataGrid;
  internal System.Windows.Controls.Primitives.StatusBar statusBar1;
  internal StatusBarItem _labelSearchProgress;
  internal StatusBarItem _labelItemsCount;
  internal TxInProgressIndicatorControl _searchProgressCtrl;
  internal System.Windows.Controls.Button _buttonConsume;
  internal System.Windows.Controls.Button _buttonClose;
  private bool _contentLoaded;

  public CUiAssignDataFromTCWindow()
  {
    this._application = new CApAssignDataFromTCApp();
    this._foundObjects = new List<CUiSearchResultObject>();
    this._propertiesManager = new CApPropertiesManager((TxWindow) this);
    this.InitializeComponent();
    this._dataGrid.DataContext = (object) this._model;
    ((FrameworkElement) this._searchProgressCtrl).DataContext = (object) this._searchProgressModel;
    this._searchProgressModel.UpdateSearchProgress(false);
  }

  protected virtual void OnInitialized(EventArgs e)
  {
    base.OnInitialized(e);
    this._labelSearchProgress.Content = (object) AssignDataFromTCResources.LABEL_NO_SEARCH_PERFORMED;
    this.UpdateToolbarButtons();
    ((DispatcherObject) this).Dispatcher.BeginInvoke((Delegate) new Action(this.InitResultsDataGrid), DispatcherPriority.Background);
    ((DispatcherObject) this).Dispatcher.BeginInvoke((Delegate) new Action(this.InitSearchScopes), DispatcherPriority.Background);
    this.RegisterForEvents();
    this._textBoxItemId.Focus();
  }

  private void filterWindow_FilterSet(object sender, EventArgs e)
  {
    string searchText = this._filterWindow.SearchText;
    int columnIndex = this._filterWindow.ColumnIndex;
    if (string.IsNullOrEmpty(searchText))
      return;
    this._dataGrid.Filter(searchText, columnIndex);
  }

  private void FilterButtonClick(object sender, RoutedEventArgs e)
  {
    if (!(sender is FilterButton filterButton) || this._dataGrid.Items.Count <= 0)
      return;
    int columnIndex = this._dataGrid.GetColumnIndex(filterButton);
    if (this._filterWindow == null)
    {
      this._filterWindow = new FilterWnd();
      ((Window) this._filterWindow).Owner = (Window) this;
      this._filterWindow.FilterSet += new EventHandler<EventArgs>(this.filterWindow_FilterSet);
    }
    this._filterWindow.InitializeAndShow(columnIndex, filterButton);
  }

  private void SaveComboBoxItemProductSelectionState()
  {
    TxWindowSettings.StoreWindowValue((TxWindow) this, "AreProductStructuresSelected", (object) this._comboBoxItemProduct.IsSelected);
  }

  private bool AreProductStructuresSelected()
  {
    bool flag = CApPSSessionData.CanProductStructuresBeSelected;
    if (flag)
    {
      object obj;
      TxWindowSettings.RestoreWindowValue((TxWindow) this, nameof (AreProductStructuresSelected), ref obj);
      if (obj != null)
        flag = Convert.ToBoolean(obj);
    }
    return flag;
  }

  private void InitSearchScopes()
  {
    Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
    try
    {
      if (CApPSSessionData.GetStructuresAvailability == CApStructuresAvailability.Product)
      {
        this._comboBoxItemPlant.IsSelected = false;
        this._comboBoxStructures.Items.Remove((object) this._comboBoxItemPlant);
        this._comboBoxItemProduct.IsSelected = true;
      }
      else if (CApPSSessionData.GetStructuresAvailability == CApStructuresAvailability.Plant)
      {
        this._comboBoxItemProduct.IsSelected = false;
        this._comboBoxStructures.Items.Remove((object) this._comboBoxItemProduct);
        this._comboBoxItemPlant.IsSelected = true;
      }
      else if (this.AreProductStructuresSelected())
        this._comboBoxItemProduct.IsSelected = true;
      else
        this._comboBoxItemPlant.IsSelected = true;
    }
    catch (SystemException ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message}\n{AssignDataFromTCResources.INFO_THE_DIALOG_WILL_CLOSE}", AssignDataFromTCResources.CMD_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
      ((Window) this).Close();
    }
    finally
    {
      Mouse.OverrideCursor = (System.Windows.Input.Cursor) null;
    }
  }

  private void InitResultsDataGrid()
  {
    this._dataGrid.RemoveTextColumns();
    this._dataGrid.ClearBomLineData();
    ObservableCollection<string> observableCollection = new ObservableCollection<string>();
    foreach (CUiTCObjectProperty selectedProperty in this._propertiesManager.SelectedProperties)
    {
      if (selectedProperty.Name != CApPropertiesManager.BOM_LINE_NAME_PROPERTY)
        observableCollection.Add(selectedProperty.NiceName);
    }
    this._model.PropertyNiceNames = observableCollection;
    this._dataGrid.AddPropertyColumns();
  }

  private void _comboBoxItemProduct_Selected(object sender, RoutedEventArgs e)
  {
    this._listViewScopes.ItemsSource = (IEnumerable) CApPSSessionData.SearchScopes.ProductScopes;
  }

  private void _comboBoxItemPlant_Selected(object sender, RoutedEventArgs e)
  {
    this._listViewScopes.ItemsSource = (IEnumerable) CApPSSessionData.SearchScopes.PlantScopes;
  }

  private void _textBoxItemId_TextChanged(object sender, TextChangedEventArgs e)
  {
    this.UpdateSearchButton();
    this.UpdateStatusBarOnCriteriaChange();
  }

  private void _textBoxItemRevisionName_TextChanged(object sender, TextChangedEventArgs e)
  {
    this.UpdateSearchButton();
    this.UpdateStatusBarOnCriteriaChange();
  }

  private void CheckBox_SourceScope_Checked(object sender, RoutedEventArgs e)
  {
    this.UpdateSearchButton();
  }

  private void CheckBox_SourceScope_UnChecked(object sender, RoutedEventArgs e)
  {
    this.UpdateSearchButton();
  }

  private void _comboBoxStructures_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    this.UpdateSearchButton();
  }

  private void _buttonOptions_MouseDown(object sender, RoutedEventArgs e)
  {
    bool? nullable = ((Window) new CUiCustomizeColumnsWindow(this._propertiesManager)).ShowDialog();
    if (!nullable.HasValue || !nullable.Value)
      return;
    this.InitResultsDataGrid();
    if (this._foundObjects.Count <= 0)
      return;
    try
    {
      Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
      IEnumerable<string> propertiesList = this._propertiesManager.SelectedProperties.Select<CUiTCObjectProperty, string>((Func<CUiTCObjectProperty, string>) (prop => prop.Name));
      IDictionary<string, IDictionary<string, string>> dictionary = this._application.LoadObjectsProperties(this._foundObjects.Select<CUiSearchResultObject, string>((Func<CUiSearchResultObject, string>) (obj => obj.Uid)), propertiesList);
      foreach (CUiSearchResultObject foundObject in this._foundObjects)
      {
        IDictionary<string, string> newProperties = dictionary[foundObject.Uid];
        foundObject.LoadProperties(newProperties);
      }
      this.AddResultObjects((IEnumerable<CUiSearchResultObject>) this._foundObjects);
    }
    finally
    {
      Mouse.OverrideCursor = (System.Windows.Input.Cursor) null;
    }
  }

  private void _buttonToolbarClearFilters_MouseDown(object sender, RoutedEventArgs e)
  {
    this.ResetFilter();
  }

  private void _buttonToolbarDisplaySelected_MouseDown(object sender, RoutedEventArgs e)
  {
    this.LoadObjectsForPreview(this.GetSelectedObjects());
    foreach (CUiSearchResultObject selectedObject in this.GetSelectedObjects())
      selectedObject.Display();
    TxApplication.RefreshDisplay();
  }

  private void _buttonToolbarBlankSelected_MouseDown(object sender, RoutedEventArgs e)
  {
    foreach (CUiSearchResultObject selectedObject in this.GetSelectedObjects())
      selectedObject.Blank();
    TxApplication.RefreshDisplay();
  }

  private void _buttonToolbarDisplayOnlySelected_MouseDown(object sender, RoutedEventArgs e)
  {
    this.LoadObjectsForPreview(this.GetSelectedObjects());
    TxObjectList txObjectList = new TxObjectList();
    foreach (CUiSearchResultObject selectedObject in this.GetSelectedObjects())
    {
      if (selectedObject.IsLoaded && selectedObject.DisplayableObject != null)
        ((Collection<ITxObject>) txObjectList).Add((ITxObject) selectedObject.DisplayableObject);
    }
    new TxCommandManager().ExecuteCommandByCommandProgId("DisplayCommands.CUiDspDisplayOnly.1", (object) txObjectList, false);
    TxApplication.RefreshDisplay();
  }

  private void _buttonToolbarZoomToFit_MouseDown(object sender, RoutedEventArgs e)
  {
    TxApplication.ViewersManager.GraphicViewer.ZoomToFit();
    TxApplication.RefreshDisplay();
  }

  private void _buttonToolbarZoomToSelection_MouseDown(object sender, RoutedEventArgs e)
  {
    TxApplication.ActiveSelection.SetItems(this.GetSelectedLoadedDisplayableObjects());
    TxApplication.CommandsManager.ExecuteCommand("GraphicViewer.ZoomToSelection");
    TxApplication.RefreshDisplay();
  }

  private void _buttonToolbarRelocate_MouseDown(object sender, RoutedEventArgs e)
  {
    TxApplication.ActiveSelection.SetItems(this.GetSelectedLoadedDisplayableObjects());
    TxApplication.CommandsManager.ExecuteCommand("Placement.Relocate");
  }

  private void _buttonToolbarRestorePosition_MouseDown(object sender, RoutedEventArgs e)
  {
    foreach (CUiSearchResultObject selectedObject in this.GetSelectedObjects())
      selectedObject.RestoreInitialLocation();
    TxApplication.RefreshDisplay();
  }

  private void visibilityCB_Click(object sender, RoutedEventArgs e)
  {
    CUiSearchResultObject searchResultObject = (CUiSearchResultObject) null;
    if (this._dataGrid.CurrentItem is BomLine currentItem)
      searchResultObject = currentItem.ResultsObject;
    if (searchResultObject == null)
      return;
    if (searchResultObject.IsLoaded)
    {
      searchResultObject.ToggleDisplayState();
      TxApplication.RefreshDisplay();
    }
    else
      this.LoadObjectsForPreview((IEnumerable<CUiSearchResultObject>) new List<CUiSearchResultObject>()
      {
        searchResultObject
      });
    currentItem.ObjVisibility = (TxVisibilityState) searchResultObject.Visibility;
  }

  private void AddResultObjects(IEnumerable<CUiSearchResultObject> resultObjects)
  {
    this._labelItemsCount.Content = (object) string.Format(AssignDataFromTCResources.LABEL_FOUND_OBJECTS, (object) this._foundObjects.Count.ToString());
    int count = this._dataGrid.Items.Count;
    foreach (CUiSearchResultObject resultObject in resultObjects)
    {
      BomLine bomLine = new BomLine();
      List<string> stringList = new List<string>();
      bomLine.ObjVisibility = (TxVisibilityState) resultObject.Visibility;
      resultObject.RowIndex = count;
      foreach (CUiTCObjectProperty selectedProperty in this._propertiesManager.SelectedProperties)
      {
        if (selectedProperty.Name == CApPropertiesManager.BOM_LINE_NAME_PROPERTY)
        {
          bomLine.Icon = TxImageUtilitiesEx.ImageToImageSource(resultObject.SourceObjectIcon);
          bomLine.SourceStructureIcon = TxImageUtilitiesEx.ImageToImageSource(resultObject.SourceScope.Image);
          bomLine.Name = resultObject.GetProperty(selectedProperty.Name);
          bomLine.SourceStructureName = resultObject.SourceScope.NiceName;
        }
        else
          stringList.Add(resultObject.GetProperty(selectedProperty.Name));
      }
      bomLine.PropertyValues = stringList;
      bomLine.ResultsObject = resultObject;
      resultObject.VisibilityChanged += new Action<CUiSearchResultObject>(this.obj_VisibilityChanged);
      resultObject.LocationChanged += new Action<CUiSearchResultObject>(this.obj_LocationChanged);
      this._model.AddBomLine(bomLine);
      ++count;
    }
  }

  private void obj_VisibilityChanged(CUiSearchResultObject obj)
  {
    this._dataGrid.SetObjectVisibility(obj.RowIndex, (TxVisibilityState) obj.Visibility);
    this.UpdateToolbarButtons();
  }

  private void obj_LocationChanged(CUiSearchResultObject obj) => this.UpdateToolbarButtons();

  private void ResetFilter() => this._dataGrid.RemoveFilter();

  private void _dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    this.SynchSelection();
    this.UpdateToolbarButtons();
    this.UpdateConsumeButton();
  }

  private void SynchSelection()
  {
    if (this._dataGrid.SelectedItems.Count > 0)
    {
      IEnumerable<CUiSearchResultObject> selectedObjects = this.GetSelectedObjects();
      TxObjectList txObjectList = new TxObjectList();
      foreach (CUiSearchResultObject searchResultObject in selectedObjects)
      {
        if (searchResultObject.DisplayableObject != null)
          ((Collection<ITxObject>) txObjectList).Add((ITxObject) searchResultObject.DisplayableObject);
      }
      if (((Collection<ITxObject>) txObjectList).Count > 0)
        TxApplication.ActiveSelection.SetItems(txObjectList);
      else
        TxApplication.ActiveSelection.Clear();
    }
    else
      TxApplication.ActiveSelection.Clear();
  }

  private IEnumerable<CUiSearchResultObject> GetSelectedObjects()
  {
    List<CUiSearchResultObject> selectedObjects = new List<CUiSearchResultObject>();
    foreach (object selectedItem in (IEnumerable) this._dataGrid.SelectedItems)
    {
      if (selectedItem is BomLine bomLine)
      {
        CUiSearchResultObject resultsObject = bomLine.ResultsObject;
        if (resultsObject != null)
          selectedObjects.Add(resultsObject);
      }
    }
    return (IEnumerable<CUiSearchResultObject>) selectedObjects;
  }

  private TxObjectList GetSelectedLoadedDisplayableObjects()
  {
    TxObjectList displayableObjects = new TxObjectList();
    foreach (CUiSearchResultObject selectedObject in this.GetSelectedObjects())
    {
      if (selectedObject.IsLoaded && selectedObject.DisplayableObject != null)
        ((Collection<ITxObject>) displayableObjects).Add((ITxObject) selectedObject.DisplayableObject);
    }
    return displayableObjects;
  }

  private void _buttonStart_Click(object sender, RoutedEventArgs e)
  {
    if (this._isSearching)
      return;
    this._isSearching = true;
    this.UpdateDialogOnSearch();
    TxTcDataImporterEx.ClearPreviewData();
    TxApplication.RefreshDisplay();
    this._application.ObjectsReceived += new Action<CApResultObjectsEventArgs>(this.CApAssignDataFromTCApp_ObjectsReceived);
    this._application.StartSearch(this._textBoxItemId.Text, this._textBoxItemRevisionName.Text, this._listViewScopes.Items.OfType<CUiSearchScope>().Where<CUiSearchScope>((Func<CUiSearchScope, bool>) (x => x.Checked)), this._propertiesManager.SelectedProperties.Select<CUiTCObjectProperty, string>((Func<CUiTCObjectProperty, string>) (prop => prop.Name)));
    ((UIElement) this).UpdateLayout();
  }

  private void _buttonSearchStop_Click(object sender, RoutedEventArgs e)
  {
    if (!this._isSearching)
      return;
    this._application.StopSearch();
  }

  private void CApAssignDataFromTCApp_ObjectsReceived(CApResultObjectsEventArgs args)
  {
    ((DispatcherObject) this).Dispatcher.Invoke(DispatcherPriority.Normal, (Delegate) new Action<CApResultObjectsEventArgs>(this.HandleSearchResults), (object) args);
  }

  private void HandleSearchResults(CApResultObjectsEventArgs args)
  {
    if (!this._closing)
    {
      if (args.IsFinished)
      {
        this._application.ObjectsReceived -= new Action<CApResultObjectsEventArgs>(this.CApAssignDataFromTCApp_ObjectsReceived);
        this._isSearching = false;
        this.UpdateDialogOnSearch(args.IsInterrupted);
        this.UpdateToolbarButtons();
      }
      else
      {
        List<CUiSearchResultObject> resultObjects = new List<CUiSearchResultObject>();
        foreach (TcSoaModelObjectData resultObject in args.ResultObjects)
        {
          CUiSearchResultObject searchResultObject = new CUiSearchResultObject(resultObject, args.SourceScope);
          this._propertiesManager.SelectedProperties.Select<CUiTCObjectProperty, string>((Func<CUiTCObjectProperty, string>) (prop => prop.Name));
          IDictionary<string, string> newProperties = (IDictionary<string, string>) new Dictionary<string, string>();
          for (int index = 0; index < ((IEnumerable<string>) resultObject.propertyNames).Count<string>(); ++index)
          {
            string propertyName = resultObject.propertyNames[index];
            string propertyValue = resultObject.propertyValues[index];
            newProperties.Add(propertyName, propertyValue);
          }
          searchResultObject.LoadProperties(newProperties);
          resultObjects.Add(searchResultObject);
          this._foundObjects.Add(searchResultObject);
        }
        this.AddResultObjects((IEnumerable<CUiSearchResultObject>) resultObjects);
      }
    }
    else
    {
      if (!args.IsFinished)
        return;
      this.ClearDialogData();
      ((Window) this).Close();
    }
  }

  private void LoadObjectsForPreview(IEnumerable<CUiSearchResultObject> targetObjects)
  {
    if (targetObjects.Where<CUiSearchResultObject>((Func<CUiSearchResultObject, bool>) (x => !x.IsLoaded)).Count<CUiSearchResultObject>() <= 0)
      return;
    Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
    this._mainGrid.IsEnabled = false;
    this._currentSearchProgressMessage = this._labelSearchProgress.Content != null ? this._labelSearchProgress.Content.ToString() : string.Empty;
    this._currentItemsCountMessage = this._labelItemsCount.Content != null ? this._labelItemsCount.Content.ToString() : string.Empty;
    this._labelSearchProgress.Content = (object) AssignDataFromTCResources.INFO_LOADING_OBJECTS;
    this._labelItemsCount.Content = (object) string.Empty;
    ((DispatcherObject) this).Dispatcher.BeginInvoke((Delegate) new Action<bool, IEnumerable<CUiSearchResultObject>, bool>(this._application.LoadObjects), DispatcherPriority.Background, (object) true, (object) targetObjects, (object) false);
  }

  private void _application_ObjectsLoaded(CApObjectsLoadedEventArgs args)
  {
    Mouse.OverrideCursor = (System.Windows.Input.Cursor) null;
    this._mainGrid.IsEnabled = true;
    this._labelSearchProgress.Content = (object) this._currentSearchProgressMessage;
    this._labelItemsCount.Content = (object) this._currentItemsCountMessage;
    if (args.ImportResult != null)
    {
      this.HandleResultObjects(args.ImportResult.LoadedObjects, false);
      this.HandleResultObjects(args.ImportResult.ExistingObjects, true);
      this.HandleResultObjects(args.ImportResult.NotLoadedObjects, false);
      List<string> stringList = new List<string>();
      foreach (TxTcResultObjectDataEx notLoadedObject1 in args.ImportResult.NotLoadedObjects)
      {
        TxTcResultObjectDataEx notLoadedObject = notLoadedObject1;
        string property = this._foundObjects.FirstOrDefault<CUiSearchResultObject>((Func<CUiSearchResultObject, bool>) (x => x.Uid == notLoadedObject.Uid)).GetProperty(CApPropertiesManager.BOM_LINE_NAME_PROPERTY);
        stringList.Add(property);
      }
      this.SynchSelection();
      if (stringList.Count > 0 && args.LoadedForPreview)
      {
        TxErrorWindow.ShowDialog(AssignDataFromTCResources.CMD_NAME, AssignDataFromTCResources.ERROR_PREVIEW_PROCESS_FAILED, new Hashtable()
        {
          {
            (object) AssignDataFromTCResources.ERROR_FAILED_TO_LOAD_OBJECTS,
            (object) stringList.ToArray()
          }
        }, new Hashtable(), true);
        TxErrorStackDlg.DisplayErrors();
      }
    }
    else if (args.LoadedForPreview && TxMessageBox.Show(AssignDataFromTCResources.ERROR_PREVIEW_FAILED, AssignDataFromTCResources.CMD_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand) == DialogResult.OK)
    {
      TxApplicationEx.SetFocusToMainWindow();
      TxErrorStackDlg.DisplayErrors();
    }
    this.UpdateToolbarButtons();
    this._areObjectsLoaded = true;
    TxApplication.RefreshDisplay();
  }

  private void HandleResultObjects(
    IEnumerable<TxTcResultObjectDataEx> resultObjects,
    bool existingObjects)
  {
    foreach (TxTcResultObjectDataEx resultObject1 in resultObjects)
    {
      TxTcResultObjectDataEx resultObject = resultObject1;
      CUiSearchResultObject searchResultObject = this._foundObjects.FirstOrDefault<CUiSearchResultObject>((Func<CUiSearchResultObject, bool>) (x => x.Uid == resultObject.Uid));
      if (searchResultObject != null)
      {
        searchResultObject.SetLoadData(resultObject.Object, existingObjects);
        this._dataGrid.SetObjectVisibility(searchResultObject.RowIndex, (TxVisibilityState) searchResultObject.Visibility);
      }
    }
  }

  private void UpdateSearchButton()
  {
    IEnumerable<CUiSearchScope> source = this._listViewScopes.Items.OfType<CUiSearchScope>().Where<CUiSearchScope>((Func<CUiSearchScope, bool>) (x => x.Checked));
    if ((this._textBoxItemId.Text != string.Empty || this._textBoxItemRevisionName.Text != string.Empty) && source.Count<CUiSearchScope>() > 0)
      this._buttonSearch.IsEnabled = true;
    else
      this._buttonSearch.IsEnabled = false;
  }

  private void UpdateConsumeButton()
  {
    if (this._dataGrid.SelectedItems.Count > 0 && !this._isSearching)
      this._buttonConsume.IsEnabled = true;
    else
      this._buttonConsume.IsEnabled = false;
  }

  private void UpdateDialogOnSearch(bool searchInterrupted = false)
  {
    if (this._isSearching)
    {
      this.ResetFilter();
      this._foundObjects.ForEach((Action<CUiSearchResultObject>) (x => x.Dispose()));
      this._foundObjects.Clear();
      this._dataGrid.ClearBomLineData();
      this._lastFocusedControl = this._textBoxItemId.IsFocused ? (System.Windows.Controls.Control) this._textBoxItemId : (System.Windows.Controls.Control) this._textBoxItemRevisionName;
      this._labelSearchProgress.Content = (object) AssignDataFromTCResources.LABEL_SEARCH_IN_PROGRESS;
      this._labelItemsCount.Content = (object) string.Format(AssignDataFromTCResources.LABEL_FOUND_OBJECTS, (object) this._foundObjects.Count.ToString());
      this._searchProgressModel.UpdateSearchProgress(true);
      this._textBoxItemId.IsEnabled = false;
      this._textBoxItemRevisionName.IsEnabled = false;
      this._listViewScopes.IsEnabled = false;
      this._dataGrid.IsEnabled = false;
      this._comboBoxStructures.IsEnabled = false;
      this._buttonConsume.IsEnabled = false;
      this._stackPanelResults.IsEnabled = false;
      this._buttonSearch.IsEnabled = false;
      this._buttonSearchStop.IsEnabled = true;
    }
    else
    {
      this._buttonSearch.IsEnabled = true;
      this._buttonSearchStop.IsEnabled = false;
      this._labelSearchProgress.Content = searchInterrupted ? (object) AssignDataFromTCResources.LABEL_SEARCH_INTERRUPTED : (object) AssignDataFromTCResources.LABEL_SEARCH_COMPLETED;
      this._searchProgressModel.UpdateSearchProgress(false);
      this._textBoxItemId.IsEnabled = true;
      this._textBoxItemRevisionName.IsEnabled = true;
      this._listViewScopes.IsEnabled = true;
      this._dataGrid.IsEnabled = true;
      this._comboBoxStructures.IsEnabled = true;
      this._stackPanelResults.IsEnabled = true;
      this._lastItemIdCriteria = this._textBoxItemId.Text;
      this._lastItemRevisionNameCriteria = this._textBoxItemRevisionName.Text;
      this.UpdateConsumeButton();
      if (this._lastFocusedControl != null)
        this._lastFocusedControl.Focus();
    }
    ((UIElement) this).UpdateLayout();
  }

  private void UpdateToolbarButtons()
  {
    if (this._dataGrid.SelectedItems.Count > 0)
    {
      IEnumerable<CUiSearchResultObject> selectedObjects = this.GetSelectedObjects();
      if (selectedObjects.Where<CUiSearchResultObject>((Func<CUiSearchResultObject, bool>) (x => x.Visibility == 2 || x.Visibility == 1)).Count<CUiSearchResultObject>() > 0)
        this._buttonToolbarDisplaySelected.IsEnabled = true;
      else
        this._buttonToolbarDisplaySelected.IsEnabled = false;
      if (selectedObjects.Where<CUiSearchResultObject>((Func<CUiSearchResultObject, bool>) (x => x.Visibility == null || x.Visibility == 1)).Count<CUiSearchResultObject>() > 0)
      {
        this._buttonToolbarBlankSelected.IsEnabled = true;
        this._buttonToolbarZoomToSelection.IsEnabled = true;
        this._buttonToolbarRelocate.IsEnabled = TxApplication.CommandsManager.IsCommandEnabled("Placement.PutCmd.1", true);
      }
      else
      {
        this._buttonToolbarBlankSelected.IsEnabled = false;
        this._buttonToolbarZoomToSelection.IsEnabled = false;
        this._buttonToolbarRelocate.IsEnabled = false;
      }
      if (selectedObjects.Where<CUiSearchResultObject>((Func<CUiSearchResultObject, bool>) (x => x.Visibility != 3)).Count<CUiSearchResultObject>() > 0)
        this._buttonToolbarDisplayOnlySelected.IsEnabled = true;
      else
        this._buttonToolbarDisplayOnlySelected.IsEnabled = false;
      if (selectedObjects.Where<CUiSearchResultObject>((Func<CUiSearchResultObject, bool>) (x => !x.IsAtInitialLocation)).Count<CUiSearchResultObject>() > 0)
        this._buttonToolbarRestorePosition.IsEnabled = true;
      else
        this._buttonToolbarRestorePosition.IsEnabled = false;
    }
    else
    {
      this._buttonToolbarDisplayOnlySelected.IsEnabled = false;
      this._buttonToolbarDisplaySelected.IsEnabled = false;
      this._buttonToolbarBlankSelected.IsEnabled = false;
      this._buttonToolbarZoomToSelection.IsEnabled = false;
      this._buttonToolbarRelocate.IsEnabled = false;
    }
  }

  private void UpdateStatusBarOnCriteriaChange()
  {
    if (this._lastItemIdCriteria != this._textBoxItemId.Text || this._lastItemRevisionNameCriteria != this._textBoxItemRevisionName.Text)
    {
      if (this._labelSearchProgress.Content != null && this._labelSearchProgress.Content.ToString() != AssignDataFromTCResources.INFO_NOT_CONSISTENT_RESULTS)
      {
        this._currentSearchProgressMessage = this._labelSearchProgress.Content != null ? this._labelSearchProgress.Content.ToString() : string.Empty;
        this._currentItemsCountMessage = this._labelItemsCount.Content != null ? this._labelItemsCount.Content.ToString() : string.Empty;
      }
      this._labelSearchProgress.Content = (object) AssignDataFromTCResources.INFO_NOT_CONSISTENT_RESULTS;
      this._labelItemsCount.Content = (object) string.Empty;
    }
    else
    {
      if (this._labelSearchProgress.Content == null || !(this._labelSearchProgress.Content.ToString() == AssignDataFromTCResources.INFO_NOT_CONSISTENT_RESULTS))
        return;
      this._labelSearchProgress.Content = (object) this._currentSearchProgressMessage;
      this._labelItemsCount.Content = (object) this._currentItemsCountMessage;
    }
  }

  private void RegisterForEvents()
  {
    TxApplication.CommandsManager.CommandExecuted += new TxCommandsManager_CommandExecutedEventHandler(this.CommandsManager_CommandExecuted);
    TxApplication.CommandsManager.CommandExecuting += new TxCommandsManager_CommandExecutingEventHandler(this.CommandsManager_CommandExecuting);
    this._application.ObjectsLoaded += new Action<CApObjectsLoadedEventArgs>(this._application_ObjectsLoaded);
    TxApplication.ActiveDocument.Unloading += new TxDocument_UnloadingEventHandler(this.ActiveDocument_Unloading);
  }

  private void UnRegisterFromEvents()
  {
    TxApplication.CommandsManager.CommandExecuted -= new TxCommandsManager_CommandExecutedEventHandler(this.CommandsManager_CommandExecuted);
    TxApplication.CommandsManager.CommandExecuting -= new TxCommandsManager_CommandExecutingEventHandler(this.CommandsManager_CommandExecuting);
    this._application.ObjectsLoaded -= new Action<CApObjectsLoadedEventArgs>(this._application_ObjectsLoaded);
    TxApplication.ActiveDocument.Unloading -= new TxDocument_UnloadingEventHandler(this.ActiveDocument_Unloading);
  }

  private void CommandsManager_CommandExecuting(
    object sender,
    TxCommandsManager_CommandExecutingEventArgs args)
  {
    if (!(args.CommandID == "Placement.PutCmd.1"))
      return;
    this._buttonToolbarRelocate.IsEnabled = false;
  }

  private void CommandsManager_CommandExecuted(
    object sender,
    TxCommandsManager_CommandExecutedEventArgs args)
  {
    if (!(args.CommandID == "Placement.PutCmd.1"))
      return;
    this.UpdateToolbarButtons();
  }

  private void ActiveDocument_Unloading(object sender, TxDocument_UnloadingEventArgs args)
  {
    TxApplication.ActiveDocument.Unloading -= new TxDocument_UnloadingEventHandler(this.ActiveDocument_Unloading);
    ((Window) this).Close();
  }

  private Image GetResourceImage(string imagePath)
  {
    Image resourceImage = new Image();
    Uri uriSource = new Uri(imagePath, UriKind.Relative);
    resourceImage.Source = (ImageSource) new BitmapImage(uriSource);
    return resourceImage;
  }

  private void _buttonClose_Click(object sender, RoutedEventArgs e) => ((Window) this).Close();

  private void TxWindow_OnClosing(object sender, CancelEventArgs e)
  {
    if (this._closing)
      return;
    if (this._consumeForm != null && !((System.Windows.Forms.Control) this._consumeForm).IsDisposed && ((System.Windows.Forms.Control) this._consumeForm).Visible)
      ((Form) this._consumeForm).Close();
    this.SaveComboBoxItemProductSelectionState();
    this._closing = true;
    if (this._isSearching)
    {
      this._application.StopSearch();
      e.Cancel = true;
    }
    else
      this.ClearDialogData();
  }

  private void ClearDialogData()
  {
    if (this._filterWindow != null && ((FrameworkElement) this._filterWindow).IsLoaded)
    {
      this._filterWindow.FilterSet -= new EventHandler<EventArgs>(this.filterWindow_FilterSet);
      this._filterWindow.ShouldClose = true;
    }
    this._dataGrid.DetachAndCleanUpModelData(ref this._model);
    ((FrameworkElement) this._searchProgressCtrl).DataContext = (object) null;
    this._searchProgressModel = (SearchProgressModel) null;
    this._foundObjects.ForEach((Action<CUiSearchResultObject>) (x => x.Dispose()));
    this._application.Dispose();
    this.UnRegisterFromEvents();
    TxTcDataImporterEx.ClearPreviewData();
    TxApplication.RefreshDisplay();
    if (!this._areObjectsLoaded)
      return;
    TxApplication.ActiveUndoManager.ClearAllTransactions();
  }

  private void Consume_Click(object sender, RoutedEventArgs e)
  {
    List<CUiSearchResultObject> objectsForConsumption = new List<CUiSearchResultObject>();
    foreach (object selectedItem in (IEnumerable) this._dataGrid.SelectedItems)
    {
      if (selectedItem is BomLine bomLine)
        objectsForConsumption.Add(bomLine.ResultsObject);
    }
    bool isSelected = this._comboBoxItemPlant.IsSelected;
    this._consumeForm = new CUiConsumeForm((IEnumerable<CUiSearchResultObject>) objectsForConsumption, this._propertiesManager.SelectedProperties, this._application, isSelected);
    ((System.Windows.Forms.Control) this._consumeForm).Show();
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  public void InitializeComponent()
  {
    if (this._contentLoaded)
      return;
    this._contentLoaded = true;
    System.Windows.Application.LoadComponent((object) this, new Uri("/DnProcessSimulateCommands;component/assigndatafromtc/cuiassigndatafromtcwindow.xaml", UriKind.Relative));
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  internal Delegate _CreateDelegate(Type delegateType, string handler)
  {
    return Delegate.CreateDelegate(delegateType, (object) this, handler);
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IComponentConnector.Connect(int connectionId, object target)
  {
    switch (connectionId)
    {
      case 1:
        ((Window) target).Closing += new CancelEventHandler(this.TxWindow_OnClosing);
        break;
      case 2:
        this._mainGrid = (Grid) target;
        break;
      case 3:
        this._groupBoxSearchScopes = (System.Windows.Controls.GroupBox) target;
        break;
      case 4:
        this._comboBoxStructures = (System.Windows.Controls.ComboBox) target;
        this._comboBoxStructures.SelectionChanged += new SelectionChangedEventHandler(this._comboBoxStructures_SelectionChanged);
        break;
      case 5:
        this._comboBoxItemProduct = (ComboBoxItem) target;
        this._comboBoxItemProduct.Selected += new RoutedEventHandler(this._comboBoxItemProduct_Selected);
        break;
      case 6:
        this._comboBoxItemPlant = (ComboBoxItem) target;
        this._comboBoxItemPlant.Selected += new RoutedEventHandler(this._comboBoxItemPlant_Selected);
        break;
      case 7:
        this._listViewScopes = (System.Windows.Controls.ListView) target;
        break;
      case 9:
        this.label2 = (TextBlock) target;
        break;
      case 10:
        this._textBoxItemId = (System.Windows.Controls.TextBox) target;
        this._textBoxItemId.TextChanged += new TextChangedEventHandler(this._textBoxItemId_TextChanged);
        break;
      case 11:
        this.label3 = (TextBlock) target;
        break;
      case 12:
        this._textBoxItemRevisionName = (System.Windows.Controls.TextBox) target;
        this._textBoxItemRevisionName.TextChanged += new TextChangedEventHandler(this._textBoxItemRevisionName_TextChanged);
        break;
      case 13:
        this._buttonSearch = (System.Windows.Controls.Button) target;
        this._buttonSearch.Click += new RoutedEventHandler(this._buttonStart_Click);
        break;
      case 14:
        this._buttonSearchStop = (System.Windows.Controls.Button) target;
        this._buttonSearchStop.Click += new RoutedEventHandler(this._buttonSearchStop_Click);
        break;
      case 15:
        this._groupBoxSearchResults = (System.Windows.Controls.GroupBox) target;
        break;
      case 16 /*0x10*/:
        this._stackPanelResults = (System.Windows.Controls.ToolBar) target;
        break;
      case 17:
        this._buttonOptions = (System.Windows.Controls.Button) target;
        this._buttonOptions.Click += new RoutedEventHandler(this._buttonOptions_MouseDown);
        break;
      case 18:
        this._buttonToolbarClearFilters = (System.Windows.Controls.Button) target;
        this._buttonToolbarClearFilters.Click += new RoutedEventHandler(this._buttonToolbarClearFilters_MouseDown);
        break;
      case 19:
        this._buttonToolbarDisplaySelected = (System.Windows.Controls.Button) target;
        this._buttonToolbarDisplaySelected.Click += new RoutedEventHandler(this._buttonToolbarDisplaySelected_MouseDown);
        break;
      case 20:
        this._buttonToolbarBlankSelected = (System.Windows.Controls.Button) target;
        this._buttonToolbarBlankSelected.Click += new RoutedEventHandler(this._buttonToolbarBlankSelected_MouseDown);
        break;
      case 21:
        this._buttonToolbarDisplayOnlySelected = (System.Windows.Controls.Button) target;
        this._buttonToolbarDisplayOnlySelected.Click += new RoutedEventHandler(this._buttonToolbarDisplayOnlySelected_MouseDown);
        break;
      case 22:
        this._buttonToolbarZoomToSelection = (System.Windows.Controls.Button) target;
        this._buttonToolbarZoomToSelection.Click += new RoutedEventHandler(this._buttonToolbarZoomToSelection_MouseDown);
        break;
      case 23:
        this._buttonToolbarZoomToFit = (System.Windows.Controls.Button) target;
        this._buttonToolbarZoomToFit.Click += new RoutedEventHandler(this._buttonToolbarZoomToFit_MouseDown);
        break;
      case 24:
        this._buttonToolbarRestorePosition = (System.Windows.Controls.Button) target;
        this._buttonToolbarRestorePosition.Click += new RoutedEventHandler(this._buttonToolbarRestorePosition_MouseDown);
        break;
      case 25:
        this._buttonToolbarRelocate = (System.Windows.Controls.Button) target;
        this._buttonToolbarRelocate.Click += new RoutedEventHandler(this._buttonToolbarRelocate_MouseDown);
        break;
      case 26:
        this._dataGrid = (BLDataGrid) target;
        break;
      case 28:
        this.statusBar1 = (System.Windows.Controls.Primitives.StatusBar) target;
        break;
      case 29:
        this._labelSearchProgress = (StatusBarItem) target;
        break;
      case 30:
        this._labelItemsCount = (StatusBarItem) target;
        break;
      case 31 /*0x1F*/:
        this._searchProgressCtrl = (TxInProgressIndicatorControl) target;
        break;
      case 32 /*0x20*/:
        this._buttonConsume = (System.Windows.Controls.Button) target;
        this._buttonConsume.Click += new RoutedEventHandler(this.Consume_Click);
        break;
      case 33:
        this._buttonClose = (System.Windows.Controls.Button) target;
        this._buttonClose.Click += new RoutedEventHandler(this._buttonClose_Click);
        break;
      default:
        this._contentLoaded = true;
        break;
    }
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IStyleConnector.Connect(int connectionId, object target)
  {
    if (connectionId != 8)
    {
      if (connectionId != 27)
        return;
      ((System.Windows.Controls.Primitives.ButtonBase) target).Click += new RoutedEventHandler(this.visibilityCB_Click);
    }
    else
    {
      ((ToggleButton) target).Checked += new RoutedEventHandler(this.CheckBox_SourceScope_Checked);
      ((ToggleButton) target).Unchecked += new RoutedEventHandler(this.CheckBox_SourceScope_UnChecked);
    }
  }
}
